package book;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

import screen.Colors;

public class BookScreen extends Canvas {

	private static int SCREEN_HEIGHT = 250;
	private static int SCREEN_WIDTH = 240;
	private static int SIDE_MARGIN = 10;
	private static int INNER_SCREEN_WIDTH = SCREEN_WIDTH - SIDE_MARGIN * 2;

	private boolean alreadySetup = false;
	private int numLineOnScreen;
	private Graphics g;
	int lineIndix = 0;
	private String phrase;
	private String[] phraseChunks;
	private int phraseChunkLength = -1;

	protected void paint(Graphics someg) {
		g = someg;
		if (!alreadySetup) {
			setup();
		}
		if (phrase == null) {
			return;
		}
		splitPhrase();
		if ((lineIndix + phraseChunkLength) <= numLineOnScreen) {
			WritePhraseFomIndix();
		} else {
			eraseSlate();
			lineIndix = 0;
			WritePhraseFomIndix();

		}
		lineIndix = lineIndix + phraseChunkLength;
	}

	private void WritePhraseFomIndix() {
		g.setColor(Colors.DARK_GREY);
		for (int i = 0; i < phraseChunkLength; i++) {
			g.drawString(phraseChunks[i], SIDE_MARGIN, SIDE_MARGIN
					+ g.getFont().getHeight() * (lineIndix + i), Graphics.LEFT
					| Graphics.TOP);
		}
	}

	private void eraseSlate() {
		int previousColor = g.getColor();
		g.setColor(Colors.WHITE);
		g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
		g.setColor(previousColor);
	}

	private void splitPhrase() {
		phraseChunks = new String[300];
		String phraseEnd = phrase;
		int index = 0;

		while (getWidth(phraseEnd) > INNER_SCREEN_WIDTH) {
			String chunk = null;
			boolean isChunkDone = false;

			while (!isChunkDone) {
				int blankIndex = phraseEnd.indexOf(" ");

				if (blankIndex < 0) {
					isChunkDone = true;
				} else {
					String candidateChunk;

					if (chunk == null) {
						candidateChunk = phraseEnd.substring(0, blankIndex);
					} else {
						candidateChunk = chunk + " "
								+ phraseEnd.substring(0, blankIndex);
					}

					if (getWidth(candidateChunk) < INNER_SCREEN_WIDTH) {
						chunk = candidateChunk;
						phraseEnd = phraseEnd.substring(blankIndex + 1);
					} else {
						isChunkDone = true;
					}
				}

			}
			phraseChunks[index++] = chunk;
		}
		phraseChunks[index++] = phraseEnd;
		phraseChunkLength = index;
	}

	private int getWidth(String phraseEnd) {
		return g.getFont().stringWidth(phraseEnd);
	}

	private void setup() {
		numLineOnScreen = 8;
//		numLineOnScreen = (SCREEN_HEIGHT - SIDE_MARGIN * 2) / g.getFont().getSize();
//		book.debugAlert("NUm line on screen : " + numLineOnScreen);
		eraseSlate();
		alreadySetup = true;
	}

	public void displayPhrase(String aPhrase) {
		phrase = aPhrase.trim();
		repaint();
	}

}
